import functools
import datetime
import time
from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for, jsonify, json
)
from werkzeug.security import check_password_hash, generate_password_hash
from werkzeug.exceptions import HTTPException
from flaskr.db import get_db
import random
import requests
import base64

bp = Blueprint('auth', __name__, url_prefix='/')

# test 
@bp.route('/tt')
def tt():
    return render_template('raspiberry vedio/airesult.html', AIresult="柠檬")


@bp.route('/api/ai')
def ai():
    # get pic
    url = 'http://192.168.137.136:8080/?action=snapshot'
    res = requests.get(url)

    content = res.content

    with open('./flaskr/pic/AAA.jpg', 'wb') as f:
        f.write(content)
        print("保存完成！")
        f.close()

    # get api ,return json result
    f = open('./flaskr/pic/AAA.jpg', 'rb')
    img = base64.b64encode(f.read())
    print(img)
    params = {"image": img}

    request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/classify/ingredient"
    access_token = '24.89baf6fc333722efdb0316c6468f6964.2592000.1605835458.282335-22851374'
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)

    if response:
        res = response.json()
        # print(res)
    ret = '识别的结果为:'+res['result'][0]['name']
    return render_template('raspiberry vedio/airesult.html', AIresult=ret)
    # return {
    #     "code": 200,
    #     "base64": img,
    #     "ret": ret,
    # }


@bp.route('/api/data')
def getdata():
    tempture = '{:.2f} 摄氏度'.format(random.uniform(30, 40))
    humidity = '{:.2f} 湿度值'.format(random.uniform(40, 50))
    # now = datetime.datetime.now()
    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    return {
        "tempture": tempture,
        "humidity": humidity,
        "time": now
    }


@bp.route('/', methods=('GET', 'POST'))
def newlogin(error=None):
    param = request.form
    tempture = '{:.2f} 摄氏度'.format(random.uniform(30, 40))
    humidity = '{:.2f} 湿度值'.format(random.uniform(40, 50))
    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

    if request.method == 'POST':
        username = param.get("name")  # None
        password = param.get("pass")

        # print(param.get("regname"),param.get("name"))
        newusername = param.get("regname")
        newpassword = param.get("regpass")

        print(username, password)
        print(newusername, newpassword)
        if username != None:  # login
            db = get_db()
            error = None
            user = db.execute(
                'SELECT * FROM user WHERE username = ?', (username,)
            ).fetchone()

            if user is None:
                error = 'Incorrect username.'
            elif not check_password_hash(user['password'], password):
                error = 'Incorrect password.'
                print(error)

            if error is None:
                session.clear()
                session['user_id'] = user['id']
                return render_template('raspiberry vedio/index.html', tempture=tempture, humidity=humidity, now=now)
        if newusername != None:  # register
            db = get_db()
            error = None

            if not newusername:
                error = 'Username is required.'
                print(error)
            elif not newpassword:
                error = 'Password is required.'
                print(error)
            elif db.execute(
                'SELECT id FROM user WHERE username = ?', (newusername,)
            ).fetchone() is not None:
                error = 'User {} is already registered.'.format(newusername)
                print(error)

            if error is None:
                db.execute(
                    'INSERT INTO user (username, password) VALUES (?, ?)',
                    (newusername, generate_password_hash(newpassword))
                )
                db.commit()
                return render_template('auth/newlogin.html', error=error)

    return render_template('auth/newlogin.html', error=error)
